package com.shsoft.task;

import com.shsoft.entity.HardWareInfo;
import oshi.hardware.GlobalMemory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MemTask implements Runnable {
    @Override
    public void run() {
        GlobalMemory memory = HardWareInfo.systemInfo.getHardware().getMemory();
        try {
            Process process = new ProcessBuilder("wmic", "memorychip","get","Capacity,DeviceLocator,Manufacturer,Speed","/format:csv").start();
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            int count = 0;
            long capacity = 0;
            String ddr = "";
            int freq = 0;
            String manufacturer = "";
            while ((line = reader.readLine()) != null) {
                if (!line.trim().equals("") && !line.contains("Capacity")) {
                    String[] fields = line.split(",");
                    count++;
                    capacity = Long.parseLong(fields[1]) / 1024 / 1024 / 1024;
                    if(fields[2].indexOf("DDR") > 0){
                        ddr = fields[2].substring(fields[2].indexOf("DDR"), fields[2].indexOf("DDR") + 4);
                    }
                    if(fields[3].indexOf(" ") > 0){
                        manufacturer = fields[3].substring(0,fields[3].indexOf(" "));
                    }else {
                        manufacturer = fields[3];
                    }
                    freq = Integer.parseInt(fields[4]);
                }
            }
            HardWareInfo.memName = manufacturer + " " + ddr + " " + freq + "MHz " + capacity + "GB x " + count;
            HardWareInfo.memClock = freq;
        }catch (Exception e){
            e.printStackTrace();
        }
        while (true){
            long memAvailable = memory.getAvailable();
            long memTotal = memory.getTotal();
            HardWareInfo.memUsed = (int) (100 - (memAvailable * 100) / memTotal);
            try {
                Thread.sleep(1800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
